<template>
  <div class="admin--popup-form">
    <div v-if="isLoading" class="admin--loading">
      데이터를 불러오는 중...
    </div>

    <form v-else @submit.prevent="handleSubmit" class="admin--form">
      <!-- 형태 -->
      <div class="admin--form-group">
        <label class="admin--form-label">형태 <span class="admin--required">*</span></label>
        <div class="admin--radio-group">
          <label class="admin--radio-label">
            <input
              v-model="formData.type"
              type="radio"
              value="html"
              name="type"
            >
            <span>HTML</span>
          </label>
          <label class="admin--radio-label">
            <input
              v-model="formData.type"
              type="radio"
              value="image"
              name="type"
            >
            <span>단일페이지</span>
          </label>
        </div>
      </div>

      <!-- 제목 -->
      <div class="admin--form-group">
        <label class="admin--form-label">제목 <span class="admin--required">*</span></label>
        <input
          v-model="formData.title"
          type="text"
          class="admin--form-input"
          placeholder="팝업 제목을 입력하세요"
          required
        >
      </div>

      <!-- 시작일/종료일 -->
      <div class="admin--form-group">
        <label class="admin--form-label">시작일/종료일 <span class="admin--required">*</span></label>
        <div class="admin--date-range">
          <DatePicker
            v-model="formData.start_date"
            placeholder="시작일 선택"
            :max-date="formData.end_date"
            required
          />
          <span class="admin--date-separator">~</span>
          <DatePicker
            v-model="formData.end_date"
            placeholder="종료일 선택"
            :min-date="formData.start_date"
            required
          />
        </div>
      </div>

      <!-- 팝업창 사이즈 -->
      <div class="admin--form-group">
        <label class="admin--form-label">팝업창 사이즈 <span class="admin--required">*</span></label>
        <div class="admin--size-group">
          <div class="admin--size-item">
            <label>가로</label>
            <input
              v-model.number="formData.width"
              type="number"
              class="admin--form-input"
              placeholder="800"
              min="100"
              required
            >
            <span>px</span>
          </div>
          <div class="admin--size-item">
            <label>세로</label>
            <input
              v-model.number="formData.height"
              type="number"
              class="admin--form-input"
              placeholder="600"
              min="100"
              required
            >
            <span>px</span>
          </div>
        </div>
      </div>

      <!-- 팝업창 위치 -->
      <div class="admin--form-group">
        <label class="admin--form-label">팝업창 위치 <span class="admin--required">*</span></label>
        <div class="admin--size-group">
          <div class="admin--size-item">
            <label>TOP</label>
            <input
              v-model.number="formData.position_top"
              type="number"
              class="admin--form-input"
              placeholder="100"
              min="0"
              required
            >
            <span>px</span>
          </div>
          <div class="admin--size-item">
            <label>LEFT</label>
            <input
              v-model.number="formData.position_left"
              type="number"
              class="admin--form-input"
              placeholder="100"
              min="0"
              required
            >
            <span>px</span>
          </div>
        </div>
      </div>

      <!-- 쿠키설정 -->
      <div class="admin--form-group">
        <label class="admin--form-label">쿠키설정</label>
        <div class="admin--radio-group">
          <label class="admin--radio-label">
            <input
              v-model="formData.cookie_setting"
              type="radio"
              value="today"
              name="cookie_setting"
            >
            <span>오늘 하루 창 띄우지 않음</span>
          </label>
          <label class="admin--radio-label">
            <input
              v-model="formData.cookie_setting"
              type="radio"
              value="forever"
              name="cookie_setting"
            >
            <span>다시는 창을 띄우지 않음</span>
          </label>
          <label class="admin--radio-label">
            <input
              v-model="formData.cookie_setting"
              type="radio"
              value="none"
              name="cookie_setting"
            >
            <span>사용 안 함</span>
          </label>
        </div>
      </div>

      <!-- 출력내용 (HTML) -->
      <div v-if="formData.type === 'html'" class="admin--form-group">
        <label class="admin--form-label">출력내용 <span class="admin--required">*</span></label>
        <SunEditor
          v-model="formData.content"
          height="400px"
          placeholder="팝업 내용을 입력하세요"
        />
      </div>

      <!-- 출력내용 (이미지) -->
      <div v-if="formData.type === 'image'" class="admin--form-group">
        <label class="admin--form-label">이미지 첨부 <span class="admin--required">*</span></label>
        <input
          type="file"
          accept="image/*"
          class="admin--form-file"
          @change="handleImageUpload"
        >
        <div v-if="imagePreview || formData.image_url" class="admin--image-preview">
          <img :src="imagePreview || getImageUrl(formData.image_url)" alt="미리보기">
          <button
            type="button"
            class="admin--btn-remove-image"
            @click="removeImage"
          >
            삭제
          </button>
        </div>
      </div>

      <!-- 링크 URL (단일페이지일 경우) -->
      <div v-if="formData.type === 'image'" class="admin--form-group">
        <label class="admin--form-label">링크 URL</label>
        <input
          v-model="formData.link_url"
          type="url"
          class="admin--form-input"
          placeholder="https://example.com"
        >
      </div>

      <!-- 버튼 영역 -->
      <div class="admin--form-actions">
        <button
          type="submit"
          class="admin--btn admin--btn-primary"
          :disabled="isSaving"
        >
          {{ isSaving ? '저장 중...' : '확인' }}
        </button>
        <button
          type="button"
          class="admin--btn admin--btn-secondary"
          @click="goToList"
        >
          목록
        </button>
      </div>

      <!-- 성공/에러 메시지 -->
      <div v-if="successMessage" class="admin--alert admin--alert-success">
        {{ successMessage }}
      </div>
      <div v-if="errorMessage" class="admin--alert admin--alert-error">
        {{ errorMessage }}
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import SunEditor from '~/components/admin/SunEditor.vue'
import DatePicker from '~/components/admin/DatePicker.vue'

definePageMeta({
  layout: 'admin',
  middleware: ['auth']
})

const route = useRoute()
const router = useRouter()
const { get, put, upload } = useApi()
const { getImageUrl } = useImage()

const isLoading = ref(true)
const isSaving = ref(false)
const successMessage = ref('')
const errorMessage = ref('')
const imagePreview = ref(null)
const imageFile = ref(null)

const formData = ref({
  type: 'html',
  title: '',
  start_date: '',
  end_date: '',
  width: 800,
  height: 600,
  position_top: 100,
  position_left: 100,
  cookie_setting: 'none',
  content: '',
  image_url: '',
  link_url: ''
})

// 데이터 로드
const loadPopup = async () => {
  isLoading.value = true

  const id = route.params.id
  const { data, error } = await get(`/basic/popup/${id}`)

  console.log('[Popup Edit] 데이터 로드 응답:', { data, error })

  // API 응답: { success: true, data: {...}, message }
  if (data?.success && data?.data) {
    const popup = data.data
    formData.value = {
      type: popup.type || 'html',
      title: popup.title || '',
      start_date: popup.start_date || '',
      end_date: popup.end_date || '',
      width: popup.width || 800,
      height: popup.height || 600,
      position_top: popup.position_top || 100,
      position_left: popup.position_left || 100,
      cookie_setting: popup.cookie_setting || 'none',
      content: popup.content || '',
      image_url: popup.image_url || '',
      link_url: popup.link_url || ''
    }

    // 이미지 미리보기 설정
    if (popup.type === 'image' && popup.image_url) {
      imagePreview.value = popup.image_url
      console.log('[Popup Edit] 이미지 URL:', popup.image_url)
      console.log('[Popup Edit] 이미지 미리보기 설정:', imagePreview.value)
    }

    console.log('[Popup Edit] 데이터 로드 성공:', formData.value)
  } else {
    console.log('[Popup Edit] 데이터 로드 실패')
  }

  isLoading.value = false
}

// 이미지 업로드
const handleImageUpload = (event) => {
  const file = event.target.files[0]
  if (!file) return

  if (!file.type.startsWith('image/')) {
    alert('이미지 파일만 업로드 가능합니다.')
    return
  }

  imageFile.value = file

  // 미리보기
  const reader = new FileReader()
  reader.onload = (e) => {
    imagePreview.value = e.target.result
  }
  reader.readAsDataURL(file)
}

// 이미지 삭제
const removeImage = () => {
  imagePreview.value = null
  imageFile.value = null
  formData.value.image_url = ''
}

// 폼 제출
const handleSubmit = async () => {
  successMessage.value = ''
  errorMessage.value = ''

  // 유효성 검사
  if (!formData.value.title) {
    errorMessage.value = '제목을 입력하세요.'
    return
  }

  if (!formData.value.start_date || !formData.value.end_date) {
    errorMessage.value = '시작일과 종료일을 선택하세요.'
    return
  }

  if (formData.value.type === 'html' && !formData.value.content) {
    errorMessage.value = '출력내용을 입력하세요.'
    return
  }

  if (formData.value.type === 'image' && !imageFile.value && !formData.value.image_url) {
    errorMessage.value = '이미지를 첨부하세요.'
    return
  }

  isSaving.value = true

  try {
    let imageUrl = formData.value.image_url

    // 이미지 업로드 (새로운 이미지가 있는 경우)
    if (formData.value.type === 'image' && imageFile.value) {
      const formDataImage = new FormData()
      formDataImage.append('file', imageFile.value)

      const { data: uploadData, error: uploadError } = await upload('/upload/image', formDataImage)

      console.log('[Popup Edit] 이미지 업로드 응답:', { uploadData, uploadError })

      if (uploadError || !uploadData?.success) {
        errorMessage.value = uploadError?.message || '이미지 업로드에 실패했습니다.'
        isSaving.value = false
        return
      }

      imageUrl = uploadData.data?.url || uploadData.data
    }

    // 팝업 수정
    const submitData = {
      ...formData.value,
      image_url: imageUrl
    }

    const id = route.params.id
    const { data, error } = await put(`/basic/popup/${id}`, submitData)

    if (error || !data?.success) {
      errorMessage.value = error?.message || data?.message || '수정에 실패했습니다.'
    } else {
      successMessage.value = data.message || '팝업이 수정되었습니다.'
      setTimeout(() => {
        router.push('/admin/basic/popup')
      }, 1000)
    }
  } catch (error) {
    errorMessage.value = '서버 오류가 발생했습니다.'
    console.error('Save error:', error)
  } finally {
    isSaving.value = false
  }
}

// 목록으로 이동
const goToList = () => {
  router.push('/admin/basic/popup')
}

onMounted(() => {
  loadPopup()
})
</script>
